<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\finance\PayableExpressCustomsModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ExpressCustoms extends Controller
{
    /**
     * 快件报关列表
     */
    public function list(Request $request)
    {
        $date_start = $request->input('date_start', '');
        $date_end = $request->input('date_end', '');
        $plate_number = $request->input('plate_number', '');
        $location = $request->input('location', '');
        $agent_id = $request->input('agent_id', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableExpressCustomsModel::with(['createAdmin', 'agent']);

        if ($date_start && $date_end) {
            $query->whereBetween('customs_date', [$date_start, $date_end]);
        }

        if ($plate_number) {
            $query->where('plate_number', 'like', "%{$plate_number}%");
        }

        if ($location) {
            $query->where('location', 'like', "%{$location}%");
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()
            ->map(function($item) {
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'customs_date' => $item->customs_date,
                    'plate_number' => $item->plate_number,
                    'fee' => $item->fee,
                    'location' => $item->location,
                    'remarks' => $item->remarks,
                    'status' => $item->status,
                    'status_name' => PayableExpressCustomsModel::STATUS_LIST[$item->status] ?? '',
                    'pay_amount' => $item->pay_amount,
                    'created_admin_id' => $item->created_admin_id,
                    'created_admin_name' => $item->createAdmin->name ?? '',
                    'created_at' => $item->created_at->format('Y-m-d H:i:s')
                ];
            });

        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加快件报关记录
     */
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'customs_date' => 'required|date',
            'plate_number' => 'required|string',
            'fee' => 'required|numeric|min:0',
            'location' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $customs = new PayableExpressCustomsModel();
            $customs->agent_id = $request->input('agent_id');
            $customs->customs_date = $request->input('customs_date');
            $customs->plate_number = $request->input('plate_number');
            $customs->fee = $request->input('fee');
            $customs->location = $request->input('location');
            $customs->remarks = trim($request->input('remarks', ''));
            $customs->status = PayableExpressCustomsModel::STATUS_UNPAID;
            $customs->pay_amount = 0;
            $customs->created_admin_id = $request->get('auth')->id;
            $customs->save();

            return $this->success($customs);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新快件报关记录
     */
    public function update(Request $request, $id)
    {
        $customs = PayableExpressCustomsModel::find($id);
        if (!$customs) {
            return $this->error('快件报关记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'customs_date' => 'required|date',
            'plate_number' => 'required|string',
            'fee' => 'required|numeric|min:0',
            'location' => 'required|string',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        try {
            $customs->agent_id = $request->input('agent_id');
            $customs->customs_date = $request->input('customs_date');
            $customs->plate_number = $request->input('plate_number');
            $customs->fee = $request->input('fee');
            $customs->location = $request->input('location');
            $customs->remarks = trim($request->input('remarks', ''));
            $customs->save();

            return $this->success($customs);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除快件报关记录
     */
    public function delete($id)
    {
        $customs = PayableExpressCustomsModel::find($id);
        if (!$customs) {
            return $this->error('快件报关记录不存在');
        }

        if ($customs->status != PayableExpressCustomsModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $customs->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 获取快件报关详情
     */
    public function detail($id)
    {
        $customs = PayableExpressCustomsModel::with(['createAdmin', 'agent'])->find($id);
        if (!$customs) {
            return $this->error('快件报关记录不存在');
        }

        $data = $customs->toArray();
        $data['agent_name'] = $customs->agent->name ?? '';
        $data['status_name'] = PayableExpressCustomsModel::STATUS_LIST[$customs->status] ?? '';
        $data['created_admin_name'] = $customs->createAdmin->name ?? '';

        return $this->success($data);
    }

    /**
     * 设置付款状态
     */
    public function setPaid(Request $request, $id)
    {
        $customs = PayableExpressCustomsModel::find($id);
        if (!$customs) {
            return $this->error('快件报关记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'pay_amount' => 'required|numeric|min:0',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        $payAmount = $request->input('pay_amount');
        $totalAmount = $customs->fee;

        // 设置付款状态
        if ($payAmount >= $totalAmount) {
            $status = PayableExpressCustomsModel::STATUS_PAID;
            $payAmount = $totalAmount; // 确保支付金额不超过总金额
        } elseif ($payAmount > 0) {
            $status = PayableExpressCustomsModel::STATUS_PART_PAID;
        } else {
            $status = PayableExpressCustomsModel::STATUS_UNPAID;
        }

        try {
            $customs->pay_amount = $payAmount;
            $customs->status = $status;
            $customs->save();

            return $this->success($customs);
        } catch (\Exception $e) {
            return $this->error('设置付款状态失败：' . $e->getMessage());
        }
    }
} 